<!--
* @FileDescription:sql查询页面，用于workspace页面
* 单井生产曲线绘制
-->
<template>
  <div class="SolowellQuery">
    <el-form>
      <el-autocomplete
        v-model="wellname"
        :fetch-suggestions="getallwellnames"
        class="inline-input"
        placeholder="输入井号"
      />
      <el-select v-model="dayormonth" placeholder="选择报表类型">
        <el-option
          v-for="item in dboptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-button :loading="querying" type="primary" @click="queryclick">
        查询
      </el-button>
      <el-alert
        :title="sql_alert_message"
        :type="alert_type"
        :style="sql_alert_display"
        show-icon
        :closable="true"
      ></el-alert>
    </el-form>
    <ag-grid-vue
      v-if="query_result"
      class="ag-theme-balham"
      :rowData="query_result"
      :columnDefs="query_columns"
      :enableRangeSelection="true"
      :defaultColDef="defaultColDef"
      style="width: 100%; height: 130px; margin-bottom: 5px"
    />
    <editable-tab ref="hot" v-if="hotsettings.data" :settings="hotsettings" />
    <echarts-dom ref="echartsDom1" :option="chart_op1" style="height: 300px" />
    <echarts-dom ref="echartsDom2" :option="chart_op2" style="height: 300px" />
  </div>
</template>

<script setup>
import { dbquery } from "@/apis/query";
import queryresnorm from "@/apis/queryresnorm";
import columnsnorm from "@/apis/columnsnorm";
import { ref, onMounted } from "vue";
import EchartsDom from "@/components/EchartsDom.vue";
import allwellnames from "@/apis/getallwellnames";
import { AgGridVue } from "ag-grid-vue3";
import EditableTab from "@/components/EditableTab.vue";

//import LineChart from "@/components/LineChart";
var hotsettings = ref();
hotsettings.value = {
  licenseKey: "non-commercial-and-evaluation",
  data: null,
  colHeaders: false,
  rowHeaders: false,
  width: "auto",
  height: "auto",
  contextMenu: true,
  manualColumnFreeze: false,
  manualColumnMove: false,
  manualColumnResize: true,
  manualRowResize: true,
  manualRowMove: true,
  dropdownMenu: false,
  filters: false,
  columnSorting: false,
  comments: false,
};
var echartsDom1 = ref();
var echartsDom2 = ref();
var hot = ref();
var wellname = ref();
var dayormonth = ref();

var chart_op1 = ref();
var chart_op2 = ref();

onMounted(() => {
  echartsDom1.value.initdom();
  echartsDom2.value.initdom();
  echartsDom1.value.plot();
});

var querying = ref(false);
var alert_type = ref("error");
const dboptions = [
  { value: "daily", label: "日报" },
  { value: "monthly", label: "月报" },
];

var sql_alert_message = ref("");
var sql_alert_display = ref("visibility:hidden");

var query_columns = ref();
var defaultColDef = ref({
  resizable: true,
  wrapText: true,
  autoHeight: true,
  editable: true,
  width: "150px",
});
var query_result = null;
var query_result1 = null;
var query_result2 = null;

var queryclick = () => {
  sql_alert_display.value = "visibility:hidden";
  sql_alert_message.value = "";
  querying.value = true;
  alert_type.value = "error";
  chart_op1.value = null;
  chart_op2.value = null;
  echartsDom1.value.clear();
  echartsDom2.value.clear();
  if (wellname.value && dayormonth.value) {
    var sql1 = "";
    var sql2 = "";
    if (dayormonth.value == "daily") {
      sql1 =
        "select RQ,日产液,日产油,含水,备注 from rb_yjsj where 井号='" +
        wellname.value +
        "' order by NY asc";
      sql2 =
        "select RQ,日注水量,干线压力,油压,套压,备注 from rb_sjsj where 井号='" +
        wellname.value +
        "' order by NY asc";
    } else if (dayormonth.value == "monthly") {
      sql1 =
        "select NY as 日期,日产水+日产油 as 日产液,含水比 as 含水,日产油,动液面,累产油,累产水,生产简况 as 备注 from m_yjsj where 井号='" +
        wellname.value +
        "' order by NY asc";
      sql2 =
        "select NY as 日期,干线压力,套压,油压,日注水量,备注 from m_sjsj where 井号='" +
        wellname.value +
        "' order by NY asc";
    }

    dbquery("dbass", "select * from JWZBB where 井号='" + wellname.value + "'")
      .catch(async (reason) => {
        sql_alert_message.value =
          sql_alert_message.value + reason.message + ";CATCH";
        sql_alert_display.value = "visibility:visible";
      })
      .then(async (result) => {
        if (result.data.err) {
          sql_alert_message.value =
            sql_alert_message.value +
            result.data.err +
            ":" +
            result.data.message +
            ";";
          sql_alert_display.value = "visibility:visible";
        } else if (result.data.rows.length == 0) {
          sql_alert_message.value = sql_alert_message.value + "油井数据为空;";
          sql_alert_display.value = "visibility:visible";
          alert_type.value = "warning";
        } else {
          query_result = queryresnorm(result.data, "dbass", "edtable");
          hotsettings.value.data = query_result;
          /*
          query_result.value = queryresnorm(result.data, "dbass", "table");
          query_columns.value = columnsnorm(
            Object.keys(query_result.value[0]),
            ["headerName", "field"],
            { sortable: true, filter: true }
          );*/
        }
      })
      .then(() => {
        hot.value.hott.hotInstance.updateSettings(hotsettings.value);
        console.log(hot.value.hott.hotInstance.getData());
      });
    dbquery("dbass", sql1)
      .catch(async (reason) => {
        sql_alert_message.value =
          sql_alert_message.value + reason.message + ";CATCH";
        sql_alert_display.value = "visibility:visible";
      })
      .then(async (result) => {
        if (result.data.err) {
          sql_alert_message.value =
            sql_alert_message.value +
            result.data.err +
            ":" +
            result.data.message +
            ";";
          sql_alert_display.value = "visibility:visible";
        } else if (result.data.rows.length == 0) {
          sql_alert_message.value = sql_alert_message.value + "油井数据为空;";
          sql_alert_display.value = "visibility:visible";
          alert_type.value = "warning";
        } else {
          query_result1 = queryresnorm(result.data, "dbass", "echarts");
          const op1 = buildoption(query_result1, "油井");
          chart_op1.value = op1;
        }
      })
      .then(async () => {
        echartsDom1.value.plot();
      });

    dbquery("dbass", sql2)
      .catch(async (reason) => {
        alert_type.value = "error";
        sql_alert_message.value =
          sql_alert_message.value + reason.message + ";CATCH";
        sql_alert_display.value = "visibility:visible";
      })
      .then(async (result) => {
        if (result.data.err) {
          alert_type.value = "error";
          sql_alert_message.value =
            sql_alert_message.value +
            result.data.err +
            ":" +
            result.data.message +
            ";";
          sql_alert_display = "visibility:visible";
          console.log(result.data.err);
        } else if (result.data.rows.length == 0) {
          sql_alert_message.value = sql_alert_message.value + "水井数据为空;";
          console.log(sql_alert_message.value);
          sql_alert_display.value = "visibility:visible";
          alert_type.value = "warning";
        } else {
          query_result2 = queryresnorm(result.data, "dbass", "echarts");
          const op2 = buildoption(query_result2, "水井");
          chart_op2.value = op2;
          console.log("水井", op2);
        }
      })
      .then(async () => {
        echartsDom2.value.plot();
      });
    querying.value = false;
  } else {
    sql_alert_message.value = "请输入井号并选择报表类型";
    sql_alert_display.value = "visibility:visible";
    querying.value = false;
  }
};
var chartcolor = {
  日产液: "green",
  日产油: "red",
  含水: "blue",
  动液面: "brown",
  干线压力: "black",
  油压: "purple",
  套压: "pink",
  日注水量: "blue",
};
function buildoption(normdata, yjsj) {
  var series = Object.keys(normdata);
  series.splice(series.indexOf("日期"), 1);
  series.splice(series.indexOf("备注"), 1);
  var offset = 0;
  var ymax = null;
  var maxmap = null;
  if (yjsj == "油井") {
    //ymax = (Math.max(...normdata["日产液"]) + 10).toFixed(0);
    maxmap = {
      //日产液: ymax,
      //日产油: ymax,
      含水: 100,
    };
  } else if (yjsj == "水井") {
    ymax = (Math.max(...normdata["干线压力"]) + 3).toFixed(0);
    maxmap = {
      干线压力: ymax,
      油压: ymax,
      套压: ymax,
    };
  }
  var op = {
    title: {
      text: wellname.value + "井生产曲线(" + yjsj + ")" + dayormonth.value,
    },
    tooltip: {
      trigger: "axis",
      axisPointer: { type: "cross" },
      backgroundColor: "rgba(255, 255, 255, 0.6)",
    },
    legend: {
      // array
      data: series,
    },
    xAxis: {
      axisTick: {
        alignWithLabel: true,
      },
      data: normdata["日期"],
    },
    yAxis: [],
    series: [
      /*
      {
        name: "sales",
        type: "bar",
        data: [5, 20, 36, 10, 10, 20],
      },
      */
    ],
  };

  series.forEach((key) => {
    var td = normdata[key];
    op.series.push({
      name: key,
      type: "line",
      data: td,
      color: chartcolor[key],
      yAxisIndex: offset,
      showSymbol: false,
    });
    op.yAxis.push({
      type: "value",
      name: key,
      splitLine: {
        show: key == "日产油" || key == "日注水量" ? true : false,
      },
      min: 0,
      max: maxmap[key],
      axisLabel: {
        formatter: key == "含水" ? "{value}%" : "{value}",
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: chartcolor[key],
        },
      },
      offset: offset * 50,
      position: "left",
    });
    offset = offset + 1;
  });
  return op;
}
const getallwellnames = (queryString, callback) => {
  const results = queryString
    ? allwellnames.filter(createFilter(queryString))
    : allwellnames;
  callback(results);
};
const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};
</script>

<style scoped>
.el-alert {
  display: inline;
  visibility: hidden;
  width: 1;
}

.el-form {
  margin-bottom: 5px;
}
</style>
